
#include <Wire.h>               // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306Wire.h"        // legacy: #include "SSD1306.h"
#include <WiFi.h>

SSD1306Wire display(0x3c, SDA, SCL);   // ADDRESS, SDA, SCL  -  SDA and SCL usually populate automatically based on your board's pins_arduino.h e.g. https://github.com/esp8266/Arduino/blob/master/variants/nodemcu/pins_arduino.h
#define DEMO_DURATION 3000
typedef void (*Demo)(void);
const char* ssid = "A618";
const char* password = "123321xx.";
const char* hostname = "esp32s3kozakemi";

int demoMode = 0;
int counter = 1;
int swapCounter = 0;
//目标百分比
int target = 50;
//显示消息
String msg = "Start connecting to WiFi";
SemaphoreHandle_t task1DoneSemaphore;
void wifiConnect(void *parameter){
   while (true) {
        Serial.println("wait");
        if (xSemaphoreTake(task1DoneSemaphore, portMAX_DELAY) == pdTRUE) {
            break; // 获取到信号量，表示task1已完成
        }
    }
  WiFi.begin(ssid, password);
  WiFi.setHostname(hostname);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    msg = "Connecting to WiFi...";
    Serial.println(msg);
  }
  msg = "Connected to WiFi!";
  Serial.println(msg);
  
  vTaskDelete(parameter);
}

void drawProgressBarDemo() {
  int progress = (counter / 5) % 100;
  if(progress>=target){
    counter=swapCounter;
    progress=target;
  }else{
    swapCounter=counter;
  }
  display.drawProgressBar(0, 20, 120, 10, progress);
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.drawString(64, 4, String(progress) + "%");
  display.drawString(64, 32, msg);
}
Demo demos[] = {drawProgressBarDemo};

void drawProgressBar(void *parameter){
  task1DoneSemaphore = xSemaphoreCreateBinary();
  xSemaphoreGive(task1DoneSemaphore); // 初始时给予信号量

  while(true){
    display.clear();
    demos[demoMode]();
    display.display();
    delay(10);
    xSemaphoreGive(task1DoneSemaphore);
    counter++;
  }
}

void setup() {
  Serial.begin(115200);
  Serial.println(msg);
  // Initialising the UI will init the display too.
  display.init();

  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  //创建连接wifi线程
  delay(1000);
  xTaskCreate(
    drawProgressBar,   /* Task function. */
    "drawProgressBar", /* String with name of task. */
    10000,     /* Stack size in bytes. */
    NULL,      /* Parameter passed as input of the task */
    1,         /* Priority of the task. */
    NULL
  );     /* Task handle. */

  xTaskCreate(
    wifiConnect,   /* Task function. */
    "wifiConnect", /* String with name of task. */
    10000,     /* Stack size in bytes. */
    NULL,      /* Parameter passed as input of the task */
    1,         /* Priority of the task. */
    NULL
  );     /* Task handle. */

}

void loop() {

}

